package com.luzhikun.exer.servlet;

import com.luzhikun.exer.bean.User;
import com.luzhikun.exer.dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "LoginServlet",value = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        // 获取前台传入的参数信息
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String vCode = request.getParameter("vCode");

        // 获取验证码session
        HttpSession session = request.getSession();
        String code = (String) session.getAttribute("code");
        System.out.println(code);
        String msg="";
        System.out.println(username);
        System.out.println(password);
        System.out.println(vCode);
        if (code.equalsIgnoreCase(vCode)){
            System.out.println(1);
            // 非空验证
            if (username!=null  &&  password!=null){
                // 调用dao层代码 验证用户名密码
                UserDao userDao=new UserDao();
                User user = userDao.userLogin(username, password);
                if (user!=null){
                    msg="登录成功";
                    request.setAttribute("msg",msg);
                    session.setAttribute("user",user);
                    response.sendRedirect(request.getContextPath()+"/index.jsp");
                }
                else {
                    msg="登录失败";
                    request.setAttribute("msg",msg);
                    response.sendRedirect(request.getContextPath()+"/login.jsp");
                }
            }

        }else {
            msg="对不起,验证码输入错误";
            request.setAttribute("msg",msg);
            response.sendRedirect(request.getContextPath()+"/login.jsp");
        }

    }
}
